/*jslint browser: true*/
/*global $, jQuery, alert, window*/
window.view = {
    "sub_id": function (value_str) {
        "use strict";
        if (value_str || value_str === "") {
            $("#sub_id").val(value_str);
        }
        return parseInt($("#sub_id").val(), 10) || 0;
    },
    "sub_body": function (value_str) {
        "use strict";
        if (value_str) {
            $("#q_body").val(value_str);
        }
        return window.trim($("#q_body").val());
    },
    "sub_image_id": function (id_value) {
        "use strict";
        if (id_value) {
            $("#upload_image").attr("href", "/link/" + id_value + "/image/")
                    .attr("name", id_value)
                    .html("图片链接,点击可查看");
            $("#upload_loading").hide();
            $("#upload_control").hide();
            $("#upload_result").show();
        } else {
            return parseInt($("#upload_image").attr("name"), 10) || 0;
        }
    },
    "sub_options": function (value_str) {
        "use strict";
        if (value_str) {
            $("#q_options").val(value_str);
        }
        return window.trim($("#q_options").val());
    },
    "sub_options_count": function (count_num) {
        "use strict";
        if (count_num) {
            $("#options_count option[value=" + count_num + "]")[0].selected = true;
        }
        return parseInt($("#options_count").val(), 10);
    },
    "sub_analysis": function (value_str) {
        "use strict";
        if (value_str) {
            $("#q_analysis").val(value_str);
        }
        return window.trim($("#q_analysis").val());
    },
    "sub_answer": function (value_str) {
        "use strict";
        if (value_str) {
            $("#q_answer option[value=" + value_str + "]")[0].selected = true;
        }
        var q_answer = $("#q_answer").val();
        return q_answer instanceof Array ? q_answer.join("") : q_answer;
    }
};
window.sync = {
    "sub_data_html": function () {
        "use strict";
        var sub_data = window.format.s2c(window.storage(window.sub_key),
                                              window.format.sub)[0];
        if (sub_data) {
            window.view.sub_id(sub_data.id);
            window.view.sub_body(sub_data.body);
            window.view.sub_image_id(sub_data.image_id);
            window.view.sub_options(sub_data.options);
            window.view.sub_options_count(sub_data.options_count);
            window.view.sub_analysis(sub_data.analysis);
            window.view.sub_answer(sub_data.answer);
        }
    }
};
window.init = {
    "global_var": function () {
        "use strict";
        var pathname = location.pathname,
            update_reg = new RegExp('^/manager/question/(' +
                                    window.category_list.join("|") +
                                    ')/([0-9]+)/sub/$'),
            reg_result_list = update_reg.exec(pathname);
        if (reg_result_list) {
            //update question
            window.is_valid = true;
            window.question_id = parseInt(reg_result_list[2], 10);
            window.question_type = reg_result_list[1];
            window.question_key = "/question/{id}/".format({id: window.question_id});
            window.sub_key = "/question/{id}/sub/".format({id: window.question_id});
            window.zTree = null;
        } else {
            throw new Error("网页错误");
        }
    },
    "url_varify": function () {
        "use strict";
        if (window.is_valid) {
            var question_key = window.question_key,
                question_data = window.format.s2c(window.storage(question_key),
                                                  window.format.question)[0],
                question_type = window.question_type,
                varify_type = window.category_list.getNameByNum(question_data.category_num),
                url = "/manager/question/{type}/{id}/sub/".format({
                    type: varify_type,
                    id: window.question_id
                });
            if (varify_type !== question_type) {
                window.location.assign(url);
            }
        }
    },
    "sub_html": function () {
        "use strict";
        if (window.is_valid) {
            window.sync.sub_data_html();
        }
    },
    "addEventListener": function () {
        "use strict";
        $("#upload_file").click(window.listener.image_upload);
        $("#upload_file_change").click(window.listener.image_upload_again);
        $("#create_sub").click(function () {
            var sub_id = window.view.sub_id,
                is_create = window.view.sub_id() === 0;
            if (is_create) {
                window.listener.create_sub();
            } else {
                window.listener.update_sub();
            }
        });
        window.hideLoading();
    }
};
window.init_func_list = ["global_var",
                         "url_varify",
                         "sub_html",
                         "addEventListener"];

function fetchSub() {
    "use strict";
    return {
        "id": window.view.sub_id(),
        "body": window.view.sub_body(),
        "image_id": window.view.sub_image_id(),
        "options": window.view.sub_options(),
        "options_count": window.view.sub_options_count(),
        "analysis": window.view.sub_analysis(),
        "answer": window.view.sub_answer()
    };
}

window.listener = {
    "image_upload": function () {
        "use strict";
        if ($("#upload_file_input").val()) {
            $("#upload_loading").show();
            $.ajaxFileUpload({
                url: '/link/upload/',
                secureuri: false,
                fileElementId: 'upload_file_input',
                dataType: 'json',
                data: {
                    name: $("#file_description").val()
                },
                async: false,
                success: function (result, status) {
                    var image_id = result.id;
                    window.view.sub_image_id(image_id);
                }
            });
        }
    },
    "image_upload_again": function () {
        "use strict";
        $("#upload_control").show();
        $("#upload_result").hide();
        $("#upload_result a").attr("href", "")
            .attr("name", "")
            .html("");
    },
    "create_sub": function () {
        "use strict";
        window.loading();
        var sub_key = window.sub_key,
            sub_data = fetchSub();
        $.ajax({
            url: sub_key,
            type: "POST",
            data: JSON.stringify(sub_data),
            dataType: "json",
            async: true,
            success: function (result, status) {
                window.storage(sub_key, result.data);
                window.location.reload();
            }
        });
    },
    "update_sub": function () {
        "use strict";
        window.loading();
        var sub_key = window.sub_key,
            sub_id =  window.view.sub_id(),
            sub_update_url = "/question/{question_id}/sub/{sub_id}/".format({
                question_id: window.question_id,
                sub_id: sub_id
            }),
            js_data = fetchSub(),
            server_data = window.storage(window.sub_key),
            transData = window.getChangedValue(js_data, server_data, window.format.sub);
        if (transData === false) {
            window.hideLoading();
            return;
        }
        $.ajax({
            url: sub_update_url,
            type: "PUT",
            data: JSON.stringify(transData),
            dataType: "json",
            async: true,
            success: function (result, status) {
                window.storage(sub_key, result.data);
                window.location.reload();
            }
        });
    },
    "char_select_show": function () {
        "use strict";
        if ($("#treeDemo").children().length) {
            $("#char_selection").blur();
            $("#zTreeContainer").show("normal");
        }
    }
};
